rm(list = ls())
library(countrycode)
library(ggmap)
library(cshapes)
library(dplyr)
library(sf)
library(tidyverse)
library(stringr)
library(foreign)
library(xlsx)
library(ggplot2)
library(cshapes)
library(scales)
library(zoo)
library(readr)
library(ggthemes)
load("data.RData")
#load("Data/paperdata_baysimput.RData")
load("AfricanCountryShapefile.RData")
load("ged171.Rdata")

####create a directory to store figures
dir.create("figures")

################################# Figure 1 #################################
###########################################################################

### trends in conflict
ucdp <- read_csv("ucdp-prio-acd-181.csv")
#2-interstate 3- internal

ucdp <- ucdp %>% 
       dplyr::select(year, type_of_conflict) %>% 
       filter(type_of_conflict == 2 | type_of_conflict == 3) %>% 
       dplyr::mutate(interstate = ifelse(type_of_conflict == 2, 1, 0),
                     intrastate = ifelse(type_of_conflict == 3, 1, 0)) %>% 
       group_by(year) %>% 
       summarise(interstate = sum(interstate),
                 intrastate = sum(intrastate))

pdf("figures/conflict.pdf", width = 17, height = 8)
ucdp %>%
       ggplot(aes(x = year)) +
       geom_vline(xintercept = 1989, linetype="dotted",
                  size=1) + 
       geom_line(aes(y = interstate), colour = "blue", linetype = 1, size = .2) + 
       geom_line(aes(y = intrastate), colour = "red", linetype = 5, size = .2) + 
       scale_x_continuous(breaks = seq(1945, 2017, 10)) +
       # Aesthetics
       labs(title = "持续进行中的国家间和国内冲突（1945-2017）", x = "年份",
            y = "冲突频次",
            caption="数据来源: UCDP/PRIO Armed Conflict Dataset") +
       theme(text = element_text(size = 13, family = "KaiTi"),
             axis.text.x = element_text(angle = 90),
             axis.text = element_text(size=16),
             axis.title=element_text(size=16)) +
       theme_tufte(base_family = "KaiTi") +
       annotate("segment", x = 1970, xend = 1975, y = 35, yend = 30,
                colour="red", arrow=arrow(length=unit(0.1, "inches"))) + 
       annotate("text", x = 1970, y = 36, parse = F, 
                label = "国内冲突",size=6, family = "KaiTi") +
       annotate("segment", x = 2000, xend = 1995, y = 9, yend = 2,
                colour="blue", arrow=arrow(length=unit(0.1, "inches"))) + 
       annotate("text", x = 2000, y = 10, parse = F, 
                label = "国际冲突",size=6,family = "KaiTi") + 
       annotate("text", x = 1989, y = 20, parse = F, 
                label = "冷战结束",size=3, family = "KaiTi") 
dev.off()


################################# Figure 2 #################################
###########################################################################

### plot the grid and overlay
library(cshapes)

#Sierra Leone
world <- cshp(date = as.Date("2010-12-31"), useGW = T)
#subset
##congo
Congo <- world[which(world@data$CNTRY_NAME == "Congo, DRC"),]
#Convert Foreign Object To An Sf Object
Congo <- st_as_sf(Congo) %>% st_transform(4267)

pts <- st_sample(Congo, size = 5) %>% st_sf

# create 55km grid - here you can substitute 200 for 50000
grid_55 <- st_make_grid(Congo, n = c(20, 20),
                        crs = 4267, what = 'polygons') %>% 
  st_sf(grid_id = 1:length(.))


# create labels for each grid_id
grid_lab <- st_centroid(grid_55) %>%
  cbind(st_coordinates(.))

## figure 2(a)
# view the sampled points, polygons and grid
pdf("figures/congo_grid2.pdf", width = 8, height = 8)
ggplot() +
  geom_sf(data = Congo, fill = 'gray', lwd = 0.05) +
  geom_sf(data = pts, color = 'red', size = 1.7) + 
  geom_sf(data = grid_55, fill = 'transparent', lwd = 0.3) +
  geom_text(data = grid_lab, aes(x = X, y = Y, label = grid_id), size = 2) +
  coord_sf() + 
  labs(title = "地理网格与刚果（金）",
       subtitle = "",
       y = "纬度", x = "经度")+
  theme(line = element_blank(),rect = element_blank(), #defien the margin line
        # axis.text = element_blank(), axis.title = element_blank(), 
        panel.background = element_blank(), panel.grid.major = element_blank(), 
        panel.grid.minor = element_blank(), axis.ticks.length = unit(0,"cm"),
        panel.spacing = unit(0, "lines"), 
        plot.title = element_text(hjust = 0.5),
        text = element_text(size=16, family = 'KaiTi'),
        plot.margin = unit(c(1,  1, 1, 1), "lines")) 
dev.off()       

## figure 2(b)
data2010 <- data %>% 
  dplyr::filter(gwno == 490 & year == 2010)
pdf("figures/congo_gid.pdf", width = 8, height = 8, family = 'KaiTi')       
plot(dat2010$xcoord, dat2010$ycoord, pch = 22,
     xlab = "经度", ylab = "纬度",col="blue",
     main = "地理网格与刚果（金）")
dev.off() 


################################# Figure 3 #################################
###########################################################################




### clean GED 
ged = ged171@data

ged <- ged %>% filter(year > 1991 & year < 2014) %>% 
       select(latitude,longitude, year, country_id, country, 
              priogrid_g, gwnoa, date_start, type_of_vi, deaths_civ)
ged$gwnoa <- as.integer(as.character(ged$gwnoa))
ged <- ged %>% filter(!is.na(gwnoa))

afric_cty <- unique(data$gwno)
ged <- ged[which(ged$gwnoa %in% afric_cty),]

ged_total <- ged %>% 
       dplyr::group_by(gwnoa) %>% 
       dplyr::summarise(violence = n())

afric_shp <- fortify(africa, region = "ISO3")
afric_shp$ccode <- countrycode(afric_shp$id, "iso3c", "cown")

afric_shp <- left_join(afric_shp, ged_total, by = c("ccode" = "gwnoa"))
afric_shp <- afric_shp[order(afric_shp$order), ] 

afric_shp$vios <- cut(afric_shp$violence,c(1, 100, 500, 1000, 2000, Inf), 
                      include.lowest = TRUE)

library(extrafont)
library(showtext)
showtext_auto(enable = TRUE)
#font_add('SimSun', 'SimSun.ttf')
font_add('KaiTi', 'KaiTi.ttf')

################################# Figure 3(a) #################################
###########################################################################

ged_month <- ged %>% 
       dplyr::mutate(state_vi = ifelse(type_of_vi ==1, 1, 0),
                     nonstate_vi = ifelse(type_of_vi == 2, 1, 0),
                     onside_vi = ifelse(type_of_vi == 3, 1, 0),
                     deaths_civ = ifelse(is.na(deaths_civ), 0, deaths_civ),
                     ymonth = format(as.Date(date_start), "%Y-%m")) %>% 
       dplyr::group_by(ymonth) %>% 
       dplyr::summarise(state_vi = sum(state_vi),
                        nonstate_vi = sum(nonstate_vi),
                        onside_vi = sum(onside_vi),
                        deaths_civ = sum(deaths_civ)) %>% 
       dplyr::mutate(dateid = row_number())

ged_month_country <- ged %>% 
       dplyr::mutate(state_vi = ifelse(type_of_vi ==1, 1, 0),
                     nonstate_vi = ifelse(type_of_vi == 2, 1, 0),
                     onside_vi = ifelse(type_of_vi == 3, 1, 0),
                     deaths_civ = ifelse(is.na(deaths_civ), 0, deaths_civ),
                     ymonth = format(as.Date(date_start), "%Y-%m")) %>% 
       dplyr::group_by(country, ymonth) %>% 
       dplyr::summarise(state_vi = sum(state_vi),
                        nonstate_vi = sum(nonstate_vi),
                        onside_vi = sum(onside_vi),
                        deaths_civ = sum(deaths_civ)) %>% 
       dplyr::mutate(dateid = row_number())


#x-label
xlabs <- seq(1, 265, 20)
xlabs2 <- unlist(ged_month[which(ged_month$dateid %in% xlabs), "ymonth"])
pdf("figures/africa_gedts.pdf", width = 17, height = 8)
ged_month %>%
       ggplot(aes(x = dateid)) +
       geom_line(aes(y = state_vi), colour = "blue", linetype = 1, size = .2) + 
       geom_line(aes(y = onside_vi), colour = "red", linetype = 5, size = .2) + 
       scale_x_continuous(breaks = seq(1, 265, 20), labels = xlabs2) +
       # Aesthetics
       labs(title = "非洲暴力冲突的时间分布（1992-2013年）", x = "月份",
            y = "频次",
            caption="作者自制",
            subtitle = "数据来源: UCDP GED") +
       theme(text = element_text(size = 13, family = "KaiTi"),
             axis.text.x = element_text(angle = 90),
             axis.text = element_text(size=16),
             axis.title=element_text(size=16)) +
       theme_tufte(base_family = "KaiTi") +
       annotate("segment", x = 61, xend = 27, y = 150, yend = 140,
                colour="red", arrow=arrow(length=unit(0.1, "inches"))) + 
       annotate("text", x = 61, y = 154, parse = F, 
                label = "单方面暴力",size=6, family = "KaiTi") +
       annotate("segment", x = 210, xend = 230, y = 100, yend = 117,
                colour="blue", arrow=arrow(length=unit(0.1, "inches"))) + 
       annotate("text", x = 200, y = 98, parse = F, 
                label = "国家暴力",size=6,family = "KaiTi") 
dev.off()


################################# Figure 3(b) #################################
###########################################################################

pdf("figures/africa_ged.pdf", width = 11, height = 8)
ggplot() + geom_polygon(data = afric_shp, 
                        aes(x = long, y = lat, group = group, 
                            fill =  vios) , 
                        size = 0.25) + coord_fixed() +
       scale_fill_manual(values = c("#009E73", "#F0E442", "#0072B2",
                                    "#D55E00", "#CC79A7"),
                         name = "暴力冲突次数", na.value="gray",
                         labels = c("1 - 100次","100 - 500次",
                                    "500 - 1000次","1000 - 2000次","大于2000次",
                                    "0次或无数据")) + 
       geom_point(aes(ged$longitude, ged$latitude,
                      color = "blue"), alpha=.5, size = 1, na.rm= TRUE) + 
       scale_color_manual(name = "暴力冲突地点",
                          labels = c("地点"),
                          values = "blue")  +
       theme(line = element_blank(),rect = element_blank(), #defien the margin line
             axis.text = element_blank(), axis.title = element_blank(), 
             panel.background = element_blank(), panel.grid.major = element_blank(), 
             panel.grid.minor = element_blank(), axis.ticks.length = unit(0,"cm"),
             panel.spacing = unit(0, "lines"), 
             text = element_text(size=16, family = 'KaiTi'),
             plot.margin = unit(c(0,  0, 0, 0), "lines")) 
dev.off()



################################# Nighttime light Figure for 2010 ##########
###########################################################################

###make a nightlight plot
night00_affica <-  data %>% filter(year == 2000) %>% 
       select(gid, nlights_mean, row, col, lan, lon)

##make as a sf object: using the sf package
coordinates(night00_affica) = ~lon+lan
night00_affica = st_as_sf(night00_affica)
pdf("figures/africa_light.pdf", width = 11, height = 8)
night00_affica %>%
       ggplot() + 
       geom_sf(aes(fill = nlights_mean, color = nlights_mean)) +
       scale_fill_gradientn(colours = c("#000233","#f9cf86","#fceccf","white") 
                            ,values = rescale(c(0,3,20,55))
                            ,breaks = c(0,3,20)
                            ,guide = FALSE) + 
       scale_color_gradientn(colours = c("#000233","#f9cf86","#fceccf","white") 
                             ,values = rescale(c(0,3,20, 55))
                             ,guide = FALSE) +
       labs(title = "非洲大陆夜间灯光分布图" 
            ,subtitle = "（以2010年为例）" ) +
       theme(text = element_text(family = "KaiTi", color = "#E1E1E1")
             ,plot.title = element_text(size = 18, color = "#E1E1E1")
             ,plot.subtitle = element_text(size = 10)
             ,plot.background = element_rect(fill = "#000223")
             ,panel.background = element_rect(fill = "#000223")
             ,panel.grid.major = element_line(color = "#000223")
             ,axis.text = element_blank()
             ,axis.ticks = element_blank()
             ,legend.background = element_blank()
       )
dev.off()



